﻿var Story =
{
    _submitStoryUrl: '',
    _loveStoryUrl: '',
    _commentStoryUrl: '',
    _centerMeTimer: null,

    set_submitStoryUrl: function (value) {
        if (Story._submitStoryUrl !== value) {
            Story._submitStoryUrl = value;
        }
    },

    set_loveStoryUrl: function (value) {
        if (Story._loveStoryUrl !== value) {
            Story._loveStoryUrl = value;
        }
    },

    set_commentStoryUrl: function (value) {
        if (Story._commentStoryUrl !== value) {
            Story._commentStoryUrl = value;
        }
    },

    init: function () {
        $addHandler($get('divSubmitStoryClose'), "click", Story._closeButtonClick);
        $addHandler($get('txtStoryTitle'), "keydown", Story._keyDown);
        $addHandler($get('txtArtistName'), "keydown", Story._keyDown);

    },

    dispose: function () {
        Story._clearCenterMeTimer();
        $removeHandler($get('divSubmitStoryClose'), "click", Story._closeButtonClick);
        $removeHandler($get('txtStoryTitle'), "keydown", Story._keyDown);
        $removeHandler($get('txtArtistName'), "keydown", Story._keyDown);
    },

    _clearCenterMeTimer: function () {
        if (Story._centerMeTimer != null) {
            clearInterval(Story._centerMeTimer);
            Story._centerMeTimer = null;
        }
    },

    _centerMe: function () {
        $U.centerIt('divSubmitStoryBox');
        Story._clearCenterMeTimer();
        Story._centerMeTimer = setInterval(
                                            function () {
                                                Story._centerMe();
                                            },
                                            500
                                          );

    },

    testForObject: function (Id, Tag) // tests if a div exists
    {
        var o = document.getElementById(Id);
        if (o) {
            if (Tag) {
                if (o.tagName.toLowerCase() == Tag.toLowerCase()) {
                    return o;
                }
            }
            else {
                return o;
            }
        }
        return null;
    },

    downloadSong: function (mp3id, storyid) {
        var url = '/Song/GetStreamMp3/' + mp3id + '/' + storyid;
        location.href = url;
//        if (!Membership.get_isLoggedIn()) {
//            Membership.showLogin();
//            return;
//        } else {
//            var url = '/Song/GetStreamMp3/' + mp3id + '/' + storyid;
//            location.href = url;
//        }
        return;
    },

    showSubmit: function () // function should be updated with new fields
    {
        if (!Membership.get_isLoggedIn()) {
            Membership.showLogin();
            return;
        }

        $U.resetInputs('divSubmitStoryBox')

        $get('ddlStoryCategory').selectedIndex = 0;
        $get('txtStoryDescription').value = '';
        var divYouTube = Story.testForObject("divYouTube"); // checks if div exists
        var divMp3Player = Story.testForObject("divMp3Player");
        if (divYouTube) {
            $U.noDisplay('divYouTube'); // hides flash components
        }
        if (divMp3Player) {
            $U.noDisplay('divMp3Player');
        }

        $U.noDisplayChidren('divSubmitStoryBox', 'span', 'validator');
        $U.noDisplayChidren('divSubmitStoryBox', 'span', 'message');

        if (Story.testForObject("divSignup"))
            $U.noDisplay('divSignup');

        $U.showModalDialog('divDimBackground', 'divSubmitStoryBox');
        Story._centerMe();

        $U.focus('txtStoryTitle');
    },

    _hide: function () {
        Story._clearCenterMeTimer();
        $U.noDisplay('divDimBackground');
        $U.noDisplay('divSubmitStoryBox');

        var divYouTube = Story.testForObject("divYouTube"); // checks if div exists
        var divMp3Player = Story.testForObject("divMp3Player");
        if (divYouTube)
            $U.display('divYouTube');
        if (divMp3Player)
            $U.display('divMp3Player');
    },

    submit: function () {

        $U.noDisplayChidren('divSubmitStoryBox', 'span', 'validator');
        $U.noDisplay('storyMessage');

        var txtTitle = $get('txtStoryTitle');
        var title = txtTitle.value.trim();

        title = title.replace("&", "amp;");

        if (title.length == 0) {
            Story._showMessage('valStoryTitle', 'Title cannot be blank.', true);
            $U.focus(txtTitle);
            return;
        }

        // new method start
        var txtArtistName = $get('txtArtistName');
        var artistName = txtArtistName.value.trim();
        artistName = artistName.replace("&", "amp;");

        if (artistName.length == 0) {
            Story._showMessage('valArtistName', 'Artist name cannot be blank.', true);
            $U.focus(txtArtistName);
            return;
        }


        var documentName = 'none';
        var imageName = 'error.gif';


        var ddlCategory = $get('ddlStoryCategory');
        var categoryId = parseInt(ddlCategory.options[ddlCategory.selectedIndex].value);

        if (categoryId < 1) {
            Story._showMessage('valStoryCategory', 'Select a category.', true);
            $U.focus(ddlCategory);
            return;
        }

        var txtDescription = $get('txtStoryDescription');
        var description = txtDescription.value.trim();

        if (description.length == 0) {
            Story._showMessage('valfStoryDescription', 'Description cannot be blank.', true);
            $U.focus(txtDescription);
            return;
        }

        var formFields = [['songTitle', title], ['storyCategoryId', categoryId], ['storyDescription', description], ['artistName', artistName]];
        Story._showMessage('storyMessage', 'Searching all over the internet...', false);
        $get('btnSubmitStory').disabled = true;

        $Ajax.post(

                        Story._submitStoryUrl,
                        formFields,
                        function (result) {

                            $get('btnSubmitStory').disabled = false;

                            if (result.isSuccessful == true) {
                                window.location = "../../../../../../Song/Upcoming/1";
                            }
                            else {
                                Story._showMessage('storyMessage', result.errorMessage, true);
                                $U.focus('txtStoryTitle');
                            }
                        },
                        function (error) {
                            $get('btnSubmitStory').disabled = false;
                            Story._showMessage('storyMessage', 'An unexpected error has occurred while submitting story.', true);
                        }
                    );
    },

    love: function (storyId, currentLove, count, it, ed, ing) {
        if (!Membership.get_isLoggedIn()) {
            Membership.showLogin();
            return;
        }

        $U.noDisplay(it);
        $U.display(ing);

        $Ajax.post(
                        Story._loveStoryUrl,
                        [['storyId', storyId]],
                        function (result) {
                            if (result.isSuccessful == true) {
                                currentLove += 1;
                                $U.setText(count, currentLove.toString());
                                $U.noDisplay(ing);
                                $U.display(ed);
                            }
                            else {
                                $U.noDisplay(ing);
                                $U.display(it);
                                alert(result.errorMessage);
                            }
                        },
                        function (error) {
                            $U.noDisplay(ing);
                            $U.display(it);
                            alert('An unexpected error has occurred while Loving the song.');
                        }
                    );
    },

    comment: function (storyId, commentBox, commentMessage) {
        if (!Membership.get_isLoggedIn()) {
            Membership.showLogin();
            return;
        }

        $U.noDisplay('commentMessage');

        var txtComment = $get('txtComment');
        var comment = txtComment.value.trim();

        if (comment.length == 0) {
            Story._showMessage('commentMessage', 'Comment cannot be blank.', true);
            $U.focus(txtComment);
            return;
        }

        Story._showMessage('commentMessage', 'Submitting comment...', false);
        $get('btnSubmitComment').disabled = true;

        $Ajax.post(
                        Story._commentStoryUrl,
                        [['storyId', storyId], ['commentContent', comment]],
                        function (result) {
                            if (result.isSuccessful == true) {
                                txtComment.value = '';
                                Story._showMessage('commentMessage', 'Thanks for submitting comments. It will appear here shortly.', false);
                            }
                            else {
                                Story._showMessage('commentMessage', result.errorMessage, true);
                                $U.focus(txtComment);
                            }

                            $get('btnSubmitComment').disabled = false;
                        },
                        function (error) {
                            Story._showMessage('commentMessage', 'An unexpected error has occurred while posting comment.', true);
                            $get('btnSubmitComment').disabled = false;
                        }
                    );
    },

    _showMessage: function (ee, msg, err) {
        var e = $U.fix(ee);

        if (err) {
            e.style.color = '#ff0000';
        }
        else {
            e.style.color = '';
        }

        $U.setText(e, msg);
        $U.display(e);
    },

    _isValidUrl: function (url) {
        var ex = new RegExp('http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?');
        var matches = ex.exec(url);

        return ((matches != null) && (url == matches[0]));
    },

    _keyDown: function (e) {
        if (e.keyCode === Sys.UI.Key.enter) {
            Story.submit();
        }
        else if (e.keyCode === Sys.UI.Key.esc) {
            Story._hide();
        }
    },

    _closeButtonClick: function (e) {
        Story._hide();
    }
}